import logging
from dataclasses import dataclass

from src.application.category.dto import CategoriesDTO
from src.application.category.interfaces import GetCategoriesFilters
from src.application.category.uow import CategoryUoW
from src.application.server.enums import ServerPrivacy, ServerType
from src.domain.common.constants import Empty, OrderBy

logger = logging.getLogger(__name__)


@dataclass(frozen=True)
class FilterCategories:
    proxy_type: ServerType | Empty = Empty.UNSET
    proxy_privacy: ServerPrivacy | Empty = Empty.UNSET
    country_id: int | Empty = Empty.UNSET
    provider_id: int | Empty = Empty.UNSET
    offset: int | Empty = Empty.UNSET
    limit: int | Empty = Empty.UNSET
    order_by: OrderBy = OrderBy.ASC


class FilterCategoriesHandler:
    def __init__(self, *, uow: CategoryUoW) -> None:
        self._uow = uow

    async def __call__(self, query: FilterCategories) -> CategoriesDTO:
        categories = await self._uow.category_reader.filter_categories(
            GetCategoriesFilters(
                proxy_type=query.proxy_type,
                proxy_privacy=query.proxy_privacy,
                country_id=query.country_id,
                provider_id=query.provider_id,
                offset=query.offset,
                limit=query.limit,
            )
        )
        logger.debug(
            "Filter categories",
            extra={
                "proxy_type": query.proxy_type,
                "proxy_privacy": query.proxy_privacy,
                "country_id": query.country_id,
                "provider_id": query.provider_id,
                "categories": categories,
                "total": len(categories),
                "offset": query.offset,
                "limit": query.limit,
            },
        )
        return CategoriesDTO(
            categories=categories,
            total=len(categories),
            offset=query.offset,
            limit=query.limit,
        )
